package internal

import (
	"context"
	"io"
	"net/http"

	"github.com/ovh/cds/engine/worker/pkg/workerruntime"
	"github.com/ovh/cds/sdk"
)

func vulnerabilityHandler(ctx context.Context, wk *CurrentWorker) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		ctx := workerruntime.SetJobID(ctx, wk.currentJob.wJob.ID)
		ctx = workerruntime.SetStepOrder(ctx, wk.currentJob.currentStepIndex)
		ctx = workerruntime.SetStepName(ctx, wk.currentJob.currentStepName)

		if r.Body == nil {
			w.WriteHeader(http.StatusBadRequest)
			return
		}
		defer r.Body.Close()

		var report sdk.VulnerabilityWorkerReport
		data, err := io.ReadAll(r.Body)
		if err != nil {
			writeError(w, r, err)
			return
		}

		if err := sdk.JSONUnmarshal(data, &report); err != nil {
			writeError(w, r, err)
			return
		}

		jobID, err := workerruntime.JobID(wk.currentJob.context)
		if err != nil {
			writeError(w, r, err)
			return
		}

		if err := wk.Client().QueueSendVulnerability(wk.currentJob.context, jobID, report); err != nil {
			writeError(w, r, err)
			return
		}
	}
}
